package cn.dzhang.spring.web.auth;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import cn.dzhang.spring.model.Authority;
import cn.dzhang.spring.model.User;

public class SpringUser implements UserDetails, CredentialsContainer {

	private static final long serialVersionUID = 8549847084307493430L;
	private User user;

	public SpringUser(User user) {
		this.user = user;
	}

	@Override
	public void eraseCredentials() {

	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		List<Authority> authorities = user.getAuthorities();
		Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
		for (Authority authority : authorities) {
			GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(
					authority.getName());
			grantedAuthorities.add(grantedAuthority);
		}

		return grantedAuthorities;
	}

	@Override
	public String getPassword() {
		return user.getPassword();
	}

	@Override
	public String getUsername() {
		return user.getUsername();
	}

	@Override
	public boolean isAccountNonExpired() {
		return !user.isExpired();
	}

	@Override
	public boolean isAccountNonLocked() {
		return !user.isLocked();
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return !user.isCredentialsExpired();
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

}
